﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Management;
using System.Net;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Data;

namespace WindowsFormsApplication24
{
    static class Extensions
    {
        internal static DataSet ToDataSet<T>(this List<T> list)
        {
            Type elementType = typeof(T);
            var ds = new DataSet();
            var t = new DataTable();
            ds.Tables.Add(t);
            elementType.GetProperties().ToList().ForEach(propInfo => t.Columns.Add(propInfo.Name, Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType));
            foreach (T item in list)
            {
                var row = t.NewRow();
                elementType.GetProperties().ToList().ForEach(propInfo => row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value);
                t.Rows.Add(row);
            }
            return ds;
        }
    }  

    static class CommonClass
    {
        public static string ConfigFileName = AppDomain.CurrentDomain.BaseDirectory + "setting.xml";

        public static bool EnableIE9()
        {
            try
            {
                int OSWidth = Convert.ToInt32(CommonClass.Detect3264());
                RegistryKey root = Registry.LocalMachine;
                string addr = "";
                switch (OSWidth)
                {
                    case 32:
                        addr = @"SOFTWARE\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION";
                        break;
                    case 64:
                        addr = @"SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION";
                        break;
                    default:
                        MessageBox.Show("错误系统位数");
                        break;
                }

                RegistryKey key = root.OpenSubKey(addr, false);
                if (key != null)
                {
                    try
                    {
                        string app = System.Reflection.Assembly.GetExecutingAssembly().Location;
                        string appname = System.IO.Path.GetFileName(Application.ExecutablePath);
                        object v = key.GetValue(appname);

                        if (v == null || Convert.ToInt32(v) != 9999)
                        {
                            key.Close();

                            key = root.OpenSubKey(addr, true);

                            key.SetValue(appname, 9999);
                            MessageBox.Show("已设置当前程序使用IE最高版本呈现网页。", "提示");
                            return false;
                        }
                        return true;
                    }
                    finally
                    {
                        key.Close();
                    }
                }
                else
                {
                    MessageBox.Show("");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("无法启用IE最高版本加载网页，请联系开发者。错误原因：\r\n" + ex.Message);
                Environment.Exit(0);
            }
            return false;
        }

        public static bool PatternSome(string pattern, string input, ref string result)
        {
            Regex r = new Regex(pattern);
            Match m = r.Match(input);
            if (m.Success)
                result = m.Value;
            return m.Success;
        }

        public static string GetNetPageResult(string url)
        {
            string result = "";
            using (WebClient client = new WebClient())
            {
                result = client.DownloadString(url);
            }
            return result;
        }

        public static string PatternStyleNo(string title)
        {
            string rawtitle = title;
            string result = "";

            List<string> ignorelist = new List<string>();
            for (int i = 0; i < 4; ++i)
            {
                string year = DateTime.Now.AddYears(-2 + i).ToString("yyyy");
                ignorelist.Add(year);
            }
            Regex reg = new Regex("[A-Za-z0-9-]{4,}");
            Match m = reg.Match(rawtitle);
            while (m.Success)
            {
                if (ignorelist.IndexOf(m.Value) == -1)
                {
                    Regex reg2 = new Regex("[A-Za-z-]+");
                    Match m2 = reg2.Match(m.Value);
                    if (m2.Success)
                    {
                        if (m2.Value != m.Value)
                            result = m.Value;
                    }
                    else
                        result = m.Value;
                }
                m = m.NextMatch();
            }
            return result;
        }

        public static HtmlElement GetElement(HtmlElement root, string tagname, string attrname, string attrvalue)
        {
            if (root != null)
            {
                foreach (HtmlElement element in root.GetElementsByTagName(tagname))
                {
                    if (element.GetAttribute(attrname) == attrvalue)
                    if (attrname == null && attrvalue == null)
                        return element;

                    string attrtempvalue=element.GetAttribute(attrname);
                    if (attrtempvalue == attrvalue)
                        return element;
                }
            }
            return null;
        }

        public static List<HtmlElement> GetElementList(HtmlElement root, string tagname, string attrname, string attrvalue)
        {
            List<HtmlElement> result = new List<HtmlElement>();
            foreach (HtmlElement element in root.GetElementsByTagName(tagname))
            {
                if (element.GetAttribute(attrname) == attrvalue)
                    result.Add(element);
            }
            return result;
        }

        public static List<HtmlElement> GetElementList(HtmlElement root, string tagname, string attrname, List<string> attrvaluelist)
        {
            List<HtmlElement> result = new List<HtmlElement>();
            foreach (HtmlElement element in root.GetElementsByTagName(tagname))
            {
                if (attrvaluelist.IndexOf(element.GetAttribute(attrname)) != -1)
                    result.Add(element);
            }
            return result;
        }

        public static HtmlElement GetElement(HtmlElementCollection elements, string tag_name, string attr_name, string attr_value)
        {
            foreach (HtmlElement e in elements)
            {
                if (e.TagName.ToLower() == tag_name.ToLower())
                {
                    if (attr_value == null && attr_name == null)
                        return e;

                    StringBuilder sb = new StringBuilder(e.OuterHtml);
                    if (attr_name != null)
                    {
                        string value = e.GetAttribute(attr_name);
                        if (value == attr_value)
                        {
                            return e;
                        }
                    }
                }
            }
            return null;
        }

        public static HtmlElement GetSomeElement(ElementInfo[] infos, HtmlElement root)
        {
            HtmlElement element = root;
            foreach (ElementInfo info in infos)
            {
                element = GetElement(element, info.TagName, info.AttributeName, info.AttributeValue);
                if (element == null)
                    break;
            }
            return element;
        }

        public class ElementInfo
        {
            public string TagName { get; set; }
            public string AttributeName { get; set; }
            public string AttributeValue { get; set; }
        }

        public static void UpdateGetDataStatus(DataGridView view)
        {
            view.DataSource = null;
            if (view.Columns.Count == 0)
                view.Columns.Add("Column1", "数据项");
            if (view.Rows.Count == 0)
                view.Rows.Add(1);
            view.Rows[0].Cells[0].Value = "正在获取...";
            Application.DoEvents();
            view.Columns.Clear();
        }

        public static void SetLinkGotoSelf(object sender)
        {
            //WebBrowser webBrowser = sender as WebBrowser;
            //if (webBrowser == null)
            //    return;
            HtmlDocument doc = sender as HtmlDocument;
            //将所有的链接的目标，指向本窗体
            foreach (HtmlElement archor in doc.Links)
            {
                archor.SetAttribute("target", "_self");
            }

            //将所有的FORM的提交目标，指向本窗体
            foreach (HtmlElement form in doc.Forms)
            {
                form.SetAttribute("target", "_self");
            }
        }

        public static string Detect3264()
        {
            ConnectionOptions oConn = new ConnectionOptions();
            ManagementScope oMs = new ManagementScope("\\\\localhost", oConn);
            ObjectQuery oQuery = new System.Management.ObjectQuery("select AddressWidth from Win32_Processor");
            ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs, oQuery);
            ManagementObjectCollection oReturnCollection = oSearcher.Get();
            string addressWidth = null;

            foreach (ManagementObject oReturn in oReturnCollection)
            {
                addressWidth = oReturn["AddressWidth"].ToString();
            }

            return addressWidth;
        }

        public static void CheckUpdate(Form main, bool nottips = false)
        {
            string app = "DataCapture8";

            string file = AppDomain.CurrentDomain.BaseDirectory + "UpdateFile2.exe";
            if (System.IO.File.Exists(file))
            {
                System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();
                info.FileName = file;
                info.Arguments = string.Format("\"{0}\" \"{1}\"", app, Application.ExecutablePath);
                info.CreateNoWindow = false;
                info.RedirectStandardOutput = true;
                info.UseShellExecute = false;
                using (System.Diagnostics.Process process = System.Diagnostics.Process.Start(info))
                {
                    string result = process.StandardOutput.ReadLine();
                    switch (result)
                    {
                        case "Updating":
                            main.Close();
                            Environment.Exit(0);
                            break;
                        case "IsLatest":
                            result = "当前版本已是最新版本";
                            break;
                    }
                    if (!nottips)
                    {
                        MessageBox.Show(result);
                    }
                }
            }
            else
            {
                MessageBox.Show("找不到更新模块，无法检测更新！");
            }
        }
    }
}
